package com.wms.transport;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.Logger;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.wms.transport.buffer.Worker;
import com.wms.transport.proxys.Standard;

/**
 * 
 * spring servlet ，异步执行，将所有request 放入 Worker（buffer）中
 *
 */
public class DelegatingServletProxy extends GenericServlet {
	
	private static final long serialVersionUID = 1L;
	
	private static final Logger logger = Logger.getLogger(DelegatingServletProxy.class);

	@Override
	public void init() throws ServletException {
		Standard.setWac(WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()));//向代理servelt中设置spring context
	}
	
	
	@Override
//	synchronized
    public void service(ServletRequest request, ServletResponse response)throws ServletException, IOException {

//		proxy.service(request, response);
		
		if(Worker.add(request.startAsync()) == 0){//将请求放入buffer中,buffer最多缓存1w，如果超过1w，抛弃request
			logger.error("buffer超过临界值，舍弃。");
			response.setContentType("application/x-www-form-urlencoded");
			response.setCharacterEncoding("UTF-8");
			PrintWriter out = response.getWriter(); 
			
			out.print("Buffer超过临界值,舍弃.");
			out.flush();
		}
		
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
